package pl.edu.agh.iosr.gamblingzone.userpanel.action;


import static org.jboss.seam.ScopeType.SESSION;

import java.util.Date;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

import pl.edu.agh.iosr.gamblingzone.dao.BettingSlipDAO;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.BettingSlipDAOBean;
import pl.edu.agh.iosr.gamblingzone.model.BettingSlip;
import pl.edu.agh.iosr.gamblingzone.model.User;

@Stateful
@Scope(SESSION)
@Name("userSlips")
@Restrict("#{identity.loggedIn}")
public class BettingSlipsViewAction implements BettingSlipsView {

	@In
	private User user;
	
	@PersistenceContext
	private EntityManager em;
	
	@DataModel
	private List<BettingSlip> slips;
	
	@DataModelSelection
	@Out(required = false)
	private BettingSlip slip;

	@Logger
	Log log;
	
	private Date beginDate;
	
	private Date endDate;
	
	@In
	private FacesMessages facesMessages;

	public List<BettingSlip> findBettingSlips() {
	    slips = user.getBettingSlips();	    
	    log.info(user.getLoginName() + " number of bettingSlips: " + slips.size());
	    return null;
	}
	
	public List<BettingSlip> findByDate() {
		log.info("Dates: " + beginDate );
		
		if((beginDate != null) && (endDate != null)){
			if(beginDate.before(endDate)) {
				BettingSlipDAO dao = new BettingSlipDAOBean();
				dao.setEntityManager(em);
				slips = dao.getBettingSlipsBetween(user,beginDate, endDate, 1);
			}else{
				facesMessages.add("Begin date should be earlier than end date");
			}
		}else {
			facesMessages.add("Both entry fields are required");
		}
		
		return null;
	}

	@Remove
	public void destroy() {
	}

	public Date getBeginDate() {
		return beginDate;
	}

	
	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	
}
